import express, { Request, Response } from 'express';
import { DatabaseConfigService } from '../services/DatabaseConfigService.js';

const router = express.Router();

// AI配置接口
interface AIConfig {
  provider: 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom';
  apiKey: string;
  model: string;
  baseUrl?: string;
  temperature?: number;
  maxTokens?: number;
  priority?: number;
  enabled?: boolean;
  maxRetries?: number;
}

// 多AI配置接口
interface MultiAIConfig {
  models: AIConfig[];
  autoSwitch: boolean;
  fallbackOnError: boolean;
  fallbackOnQuotaExhausted: boolean;
}

// 配置接口定义
interface AppConfig {
  gitUsername: string;
  aiProvider: 'google' | 'deepseek' | 'tongyi' | 'doubao' | 'wenxin';
  apiKeys: Record<string, string>;
  projects: Array<{
    id: string;
    name: string;
    path: string;
    description?: string;
  }>;
  excludePatterns: string[];
  customTemplate?: string;
  aiConfig?: AIConfig;
  multiAIConfig?: MultiAIConfig;
  customPrompts?: {
    simple?: string;
    professional?: string;
  };
  reportTemplates?: Array<{
    id: string;
    name: string;
    content: string;
    type: 'daily' | 'weekly';
  }>;
}

// 默认配置
const DEFAULT_CONFIG: AppConfig = {
  gitUsername: '',
  aiProvider: 'deepseek',
  apiKeys: {},
  projects: [],
  excludePatterns: [
    'node_modules/*',
    '.git/*',
    'dist/*',
    'build/*',
    '*.log',
    '*.tmp',
    '.DS_Store',
    'Thumbs.db'
  ],
  customTemplate: '',
  aiConfig: {
    provider: 'deepseek',
    apiKey: '',
    model: 'deepseek-chat',
    temperature: 0.7,
    maxTokens: 2000
  },
  customPrompts: {
    simple: '',
    professional: ''
  }
};

/**
 * 读取配置
 */
async function readConfig(): Promise<AppConfig> {
  try {
    console.log('🔍 开始读取配置...');
    
    // 检查数据库连接状态
    const { isDatabaseConnected } = await import('../config/database.js');
    const dbConnected = isDatabaseConnected();
    console.log('📊 数据库连接状态:', dbConnected ? '已连接' : '未连接');
    
    const config = await DatabaseConfigService.getAllConfig();
    console.log('📋 从数据库/文件读取的原始配置:', JSON.stringify(config, null, 2));
    
    // 合并配置，数据库数据优先，只有当数据库中没有值时才使用默认值
    const mergedConfig: AppConfig = {
      gitUsername: config.gitUsername !== undefined && config.gitUsername !== null ? config.gitUsername : DEFAULT_CONFIG.gitUsername,
      aiProvider: config.aiProvider !== undefined && config.aiProvider !== null ? config.aiProvider : DEFAULT_CONFIG.aiProvider,
      apiKeys: config.apiKeys !== undefined ? config.apiKeys : DEFAULT_CONFIG.apiKeys,
      projects: config.projects !== undefined ? config.projects : DEFAULT_CONFIG.projects,
      excludePatterns: config.excludePatterns !== undefined ? config.excludePatterns : DEFAULT_CONFIG.excludePatterns,
      customTemplate: config.customTemplate !== undefined ? config.customTemplate : DEFAULT_CONFIG.customTemplate,
      aiConfig: config.aiConfig !== undefined ? {
        ...DEFAULT_CONFIG.aiConfig,
        ...config.aiConfig,
        provider: (config.aiConfig.provider as 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom') || DEFAULT_CONFIG.aiConfig.provider
      } : DEFAULT_CONFIG.aiConfig,
      customPrompts: config.customPrompts !== undefined ? {
        ...DEFAULT_CONFIG.customPrompts,
        ...config.customPrompts
      } : DEFAULT_CONFIG.customPrompts
    };
    
    console.log('🔄 合并后的配置:', JSON.stringify(mergedConfig, null, 2));
    
    // 确保aiConfig.provider类型正确
    if (mergedConfig.aiConfig && mergedConfig.aiConfig.provider) {
      const providerMapping: Record<string, 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom'> = {
        'google': 'custom',
        'deepseek': 'deepseek',
        'tongyi': 'tongyi',
        'doubao': 'doubao',
        'wenxin': 'custom',
        'openai': 'openai',
        'claude': 'claude',
        'custom': 'custom'
      };
      
      const currentProvider = mergedConfig.aiConfig.provider as string;
       mergedConfig.aiConfig.provider = (providerMapping[currentProvider] || 'deepseek') as 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom';
    }
    
    return mergedConfig as AppConfig;
  } catch (error) {
    console.error('读取配置失败:', error);
    // 配置读取失败，返回默认配置
    return DEFAULT_CONFIG;
  }
}

/**
 * 保存配置
 */
async function saveConfig(config: AppConfig): Promise<void> {
  // 将配置按键值对保存
  const configEntries = Object.entries(config);
  for (const [key, value] of configEntries) {
    await DatabaseConfigService.saveConfig(key, value);
  }
}

/**
 * 获取配置
 * GET /api/config
 */
router.get('/', async (req: Request, res: Response) => {
  try {
    // 添加缓存控制头，确保不缓存配置数据
    res.set({
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    });
    
    // 从数据库读取原始配置
    const config = await DatabaseConfigService.getAllConfig() as any;
    
    // 迁移旧的模型名称
    function migrateModelName(modelName: string): string {
      const modelMigrationMap: Record<string, string> = {
        'doubao-1.6-thinking': 'doubao-seed-1-6-250615',
        'doubao-seed-1.6': 'doubao-seed-1-6-250615',
        'doubao-seed-1.6-flash': 'doubao-seed-1-6-flash-250715',
        'doubao-seed-1.6-thinking': 'doubao-seed-1-6-thinking-250715'
      };
      return modelMigrationMap[modelName] || modelName;
    }
    
    // 迁移multiAIConfig中的模型名称
    if (config.multiAIConfig && config.multiAIConfig.models) {
      config.multiAIConfig.models = config.multiAIConfig.models.map((model: any) => ({
        ...model,
        model: migrateModelName(model.model)
      }));
    }
    
    // 确保aiConfig对象完整且apiKey正确赋值
    if (config.aiProvider && config.apiKeys) {
      const providerMapping: Record<string, 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom'> = {
        'google': 'custom',
        'deepseek': 'deepseek',
        'tongyi': 'tongyi',
        'doubao': 'doubao',
        'wenxin': 'custom'
      };
      
      const mappedProvider = providerMapping[config.aiProvider] || 'deepseek';
      const apiKey = config.apiKeys[config.aiProvider] || '';
      
      // 确保aiConfig存在且apiKey正确
      if (!config.aiConfig) {
        config.aiConfig = {
          provider: mappedProvider,
          apiKey: apiKey,
          model: getDefaultModelForProvider(config.aiProvider),
          temperature: 0.7,
          maxTokens: 2000
        };
      } else {
        // 更新现有aiConfig的apiKey
        config.aiConfig.apiKey = apiKey;
        config.aiConfig.provider = mappedProvider;
        if (!config.aiConfig.model) {
          config.aiConfig.model = getDefaultModelForProvider(config.aiProvider);
        } else {
          // 迁移旧的模型名称
          config.aiConfig.model = migrateModelName(config.aiConfig.model);
        }
        // 确保temperature和maxTokens存在
        if (config.aiConfig.temperature === undefined) {
          config.aiConfig.temperature = 0.7;
        }
        if (config.aiConfig.maxTokens === undefined) {
          config.aiConfig.maxTokens = 2000;
        }
      }
    }
    
    res.json({
      success: true,
      data: config
    });
  } catch (error: any) {
    console.error('读取配置失败:', error);
    res.status(500).json({
      success: false,
      error: `读取配置失败: ${error.message}`
    });
  }
});

/**
 * 获取AI服务商对应的默认模型
 */
function getDefaultModelForProvider(provider: string): string {
  const modelMap: Record<string, string> = {
    'google': 'gemini-pro',
    'deepseek': 'deepseek-chat',
    'tongyi': 'qwen-plus',
    'doubao': 'doubao-seed-1-6-250615',
    'wenxin': 'ernie-bot-turbo'
  };
  return modelMap[provider] || 'deepseek-chat';
}

/**
 * 保存配置
 * POST /api/config
 */
router.post('/', async (req: Request, res: Response) => {
  try {
    // 添加缓存控制头
    res.set({
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    });
    
    const newConfig: AppConfig = req.body;
    
    // 验证必要字段（放宽验证，允许部分配置更新）
    // if (!newConfig.gitUsername || !newConfig.aiProvider) {
    //   return res.status(400).json({
    //     success: false,
    //     error: 'Git用户名和AI服务提供商不能为空'
    //   });
    // }
    
    // 读取现有配置
    const existingConfig = await readConfig();
    
    // 合并配置，保留现有的API密钥（如果新配置中的密钥是占位符）
    const mergedConfig: AppConfig = {
      ...existingConfig,
      ...newConfig,
      apiKeys: {
        ...existingConfig.apiKeys,
        ...Object.entries(newConfig.apiKeys).reduce((acc, [key, value]) => {
          if (value && value !== '***') {
            acc[key] = value;
          }
          return acc;
        }, {} as Record<string, string>)
      }
    };
    
    // 如果AI服务商发生变化，更新aiConfig中的模型
    const providerMapping: Record<string, 'openai' | 'deepseek' | 'claude' | 'tongyi' | 'doubao' | 'custom'> = {
      'google': 'custom',
      'deepseek': 'deepseek',
      'tongyi': 'tongyi',
      'doubao': 'doubao',
      'wenxin': 'custom'
    };
    
    const mappedProvider = providerMapping[mergedConfig.aiProvider] || 'deepseek';
    
    if (mergedConfig.aiConfig) {
      mergedConfig.aiConfig.provider = mappedProvider;
      mergedConfig.aiConfig.model = getDefaultModelForProvider(mergedConfig.aiProvider);
      // 确保temperature和maxTokens存在
      if (mergedConfig.aiConfig.temperature === undefined) {
        mergedConfig.aiConfig.temperature = 0.7;
      }
      if (mergedConfig.aiConfig.maxTokens === undefined) {
        mergedConfig.aiConfig.maxTokens = 2000;
      }
    } else {
      mergedConfig.aiConfig = {
        provider: mappedProvider,
        apiKey: mergedConfig.apiKeys[mergedConfig.aiProvider] || '',
        model: getDefaultModelForProvider(mergedConfig.aiProvider),
        temperature: 0.7,
        maxTokens: 2000
      };
    }
    
    // 保存合并后的配置
    await saveConfig(mergedConfig);
    
    res.json({
      success: true,
      message: '配置保存成功'
    });
  } catch (error: any) {
    console.error('保存配置失败:', error);
    res.status(500).json({
      success: false,
      error: `保存配置失败: ${error.message}`
    });
  }
});



/**
 * 重置配置为默认值
 * POST /api/config/reset
 */
router.post('/reset', async (req: Request, res: Response) => {
  try {
    // 添加缓存控制头
    res.set({
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    });
    
    // 重置为默认配置
    await saveConfig(DEFAULT_CONFIG);
    
    res.json({
      success: true,
      message: '配置已重置为默认值'
    });
  } catch (error: any) {
    console.error('重置配置失败:', error);
    res.status(500).json({
      success: false,
      error: `重置配置失败: ${error.message}`
    });
  }
});

export default router;